package com.zaker.touchtv.modules;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.zaker.touchtv.BaseActivity;
import com.zaker.touchtv.R;
import com.zaker.touchtv.data.AppApiClient;
import com.zaker.touchtv.data.AppCreateLiveResult;
import com.zaker.touchtv.data.CreateLiveEntry;
import com.zaker.touchtv.data.PushRtmpEntry;
import com.zaker.touchtv.db.LiveDBHelper;
import com.zaker.touchtv.modules.live.LiveActivity;
import com.zaker.touchtv.modules.login.LoginActivity;
import com.zaker.touchtv.modules.login.LoginConstants;
import com.zaker.touchtv.utils.TestDataUtils;

import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.zaker.touchtv.utils.Constants.LOG_TAG;
import static com.zaker.touchtv.utils.TestDataUtils.CREATE_LIVE_URL;

public class MainActivity extends BaseActivity {

  private ViewGroup mContentLayout;
  private TouchTvMainLayout mTouchTvMainLayout;

  private MaterialDialog mMainDialog;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

//    Log.i(LOG_TAG, " encodeBy16BitMD5 351542060438243 result is: "
//        + MD5Utils.encodeBy16BitMD5("351542060438243")
//        + " 508951b3bc5e3fd48bac5db12132fefb and 351542060438243 pushClientId is: "
//        + String.format(Locale.CHINESE, "508951b3bc5e3fd48bac5db12132fefbS%s",
//        MD5Utils.encodeBy16BitMD5("351542060438243")));

    setContentView(R.layout.activity_main);
    mContentLayout = (ViewGroup) findViewById(R.id.activity_main_layout);
    mTouchTvMainLayout = TouchTvMainLayout.newInstance(getLayoutInflater(), mContentLayout, true);

    ensureUI();
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (data == null) {
      return;
    }

    if (resultCode != LoginConstants.LOGIN_RESULT_CODE) {
      return;
    }

    final String uid = data.getStringExtra(LoginConstants.LOGIN_RESULT_OF_UID_KEY);
    final String userName = data.getStringExtra(LoginConstants.LOGIN_RESULT_OF_NAME_KEY);
    final String token = data.getStringExtra(LoginConstants.LOGIN_RESULT_OF_TOKEN_KEY);
    if (TextUtils.isEmpty(uid)) {
      return;
    }
    LiveDBHelper.saveUserInfo(uid, userName, token, getApplicationContext());
    ensureUI();

    if (requestCode == LoginConstants.LOGIN_AND_LIVE_QUEST_CODE) {
      tryToStartTestLive(false);
    }
  }

  @Override
  protected void onDestroy() {
    destroyDialog();
    super.onDestroy();
  }

  private void destroyDialog() {
    if (mMainDialog != null) {
      mMainDialog.dismiss();
      mMainDialog = null;
    }
  }

  private void startLiveActivity(String uid, String userName, String liveName) {

    Snackbar.make(getContentView(), R.string.create_live_loading_tip,
        Snackbar.LENGTH_INDEFINITE).show();

    Map<String, String> params = TestDataUtils.getCreateLiveParams(uid, userName, liveName);
    Call<AppCreateLiveResult> createLiveCall = AppApiClient.getLiveService()
        .getCreateLiveResult(CREATE_LIVE_URL, params);
    createLiveCall.enqueue(new Callback<AppCreateLiveResult>() {
      @Override
      public void onResponse(Call<AppCreateLiveResult> call, Response<AppCreateLiveResult> response) {
        AppCreateLiveResult liveResult = response.body();
        if (liveResult == null) {
          Log.i(LOG_TAG, "onResponse liveResult is null!");
          return;
        }
        CreateLiveEntry liveEntry = liveResult.getCreateLiveEntry();
        if (liveEntry == null) {
          Log.i(LOG_TAG, "onResponse liveEntry is null!");
          return;
        }
        PushRtmpEntry pushRtmpEntry = liveEntry.getPushRtmpServer();
        if (pushRtmpEntry == null) {
          Log.i(LOG_TAG, "onResponse pushRtmpEntry is null!");
          return;
        }
        final String pushUrl = pushRtmpEntry.getSite();
        if (TextUtils.isEmpty(pushUrl)) {
          Log.i(LOG_TAG, "onResponse pushUrl isEmpty!");
          return;
        }
        Snackbar.make(getContentView(), R.string.create_live_success_tip,
            Snackbar.LENGTH_SHORT).show();
        Log.i(LOG_TAG, "onResponse pushUrl : " + pushUrl);
        LiveActivity.startLiveActivity(liveEntry.getPk(), pushUrl, MainActivity.this);
      }

      @Override
      public void onFailure(Call<AppCreateLiveResult> call, Throwable t) {
        Log.i(LOG_TAG, "onFailure " + t.getMessage());
        Snackbar.make(getContentView(), R.string.create_live_fail_tip,
            Snackbar.LENGTH_LONG).show();
      }
    });
  }

  private void ensureUI() {

    final TextView loginTipView = mTouchTvMainLayout.getLoginView();
    String[] userInfo = LiveDBHelper.getUserInfo(getApplicationContext());
    if (userInfo[0] != null) {
      loginTipView.setTextColor(Color.BLUE);
      loginTipView.setText(getString(R.string.is_logged_in_tip_text, userInfo[2]));
    } else {
      loginTipView.setTextColor(Color.RED);
      loginTipView.setText(R.string.without_login_tip_text);
    }

    final TextView selectedDeviceView = mTouchTvMainLayout.getSelectedDeviceView();
    selectedDeviceView.setText(LiveDBHelper.getSelectedDeviceName(getApplicationContext()));

    try {
      PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
      mTouchTvMainLayout.setVersionName(packageInfo.versionName);
    } catch (PackageManager.NameNotFoundException e) {
      e.printStackTrace();
    }
  }

  View getContentView() {
    return getWindow().getDecorView().findViewById(android.R.id.content);
//    return mContentLayout;
  }

  public void onOnlyClickLogin(View view) {
    if (LiveDBHelper.hasLogin(getApplicationContext())) {
      LiveDBHelper.clearUserInfo(getApplicationContext());
      ensureUI();
    } else {
      LoginActivity.startLoginActivity(this, LoginConstants.LOGIN_QUEST_CODE);
    }
  }

  public void onClickTestEvent(View view) {

    tryToStartTestLive(true);
  }

  private void tryToStartTestLive(boolean shouldAutoLogin) {

    final String[] userInfo = LiveDBHelper.getUserInfo(getApplicationContext());
    if (shouldAutoLogin && userInfo[0] == null) {
      LoginActivity.startLoginActivity(this, LoginConstants.LOGIN_AND_LIVE_QUEST_CODE);
    } else if (userInfo[0] != null) {
      destroyDialog();
      final String inputHint = getString(R.string.test_live_default_name,
          String.valueOf(System.currentTimeMillis()));
      mMainDialog = new MaterialDialog.Builder(this)
          .title(R.string.create_test_live_dialog_title)
          .content(R.string.create_test_live_tip_content)
          .inputType(InputType.TYPE_CLASS_TEXT)
          .input(inputHint, null, true, new MaterialDialog.InputCallback() {
            @Override
            public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {

              if (TextUtils.isEmpty(input)) {
                input = inputHint;
              }
              startLiveActivity(userInfo[1], userInfo[2], String.valueOf(input));

              //TODO test
              //LiveActivity.startLiveActivity("", MainActivity.this);
            }
          })
          .positiveText(R.string.sure)
          .negativeText(R.string.cancel)
          .show();
    }
  }

  public void onSelectedFilmedClientEvent(View view) {

    final int selectedIndex = LiveDBHelper.getSelectedDeviceIndex(getApplicationContext());
    destroyDialog();
    mMainDialog = new MaterialDialog.Builder(this)
        .title(R.string.selected_dialog_title)
        .items(R.array.selected_filmed_device)
        .itemsCallbackSingleChoice(selectedIndex, new MaterialDialog.ListCallbackSingleChoice() {
          @Override
          public boolean onSelection(MaterialDialog dialog, View itemView, int which,
                                     CharSequence text) {
            LiveDBHelper.setSelectedDeviceIndex(which, getApplicationContext());
            mTouchTvMainLayout.getSelectedDeviceView().setText(text);
            return true;
          }
        })
        .positiveText(R.string.sure)
        .show();

  }
}
